package com.example.qqdbanner.ui;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.SDCardUtils;
import com.example.qqdbanner.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ViewPager viewPager;

    private List<String> imagePaths;

    private static final int REQUEST_CODE_PERMISSION = 100;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkPermissions();
    }

    private void checkPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_PERMISSION);
        } else {
            loadImagesFromSDCard();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
            @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                loadImagesFromSDCard();
            } else {
                // Permission denied
                Toast.makeText(this, "没开权限", Toast.LENGTH_SHORT).show();
            }
        }
    }


    private Handler handler = new Handler();
    private Runnable runnable;

    private void loadImagesFromSDCard() {

        String filePath = getExternalStorageDirectories();
        if (filePath == null) {
            Toast.makeText(this, "U盘读取错误，电视挂载U盘的方式需要适配", Toast.LENGTH_SHORT).show();
            return;
        }
        File directory = new File(filePath + "/QQD");
        if (directory.exists() && directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                imagePaths = new ArrayList<>();
                for (File file : files) {
                    if (file.isFile() && isImageFile(file.getPath())) {
                        imagePaths.add(file.getPath());
                    }
                }
                setupViewPager();
            } else {
                Toast.makeText(this, "请将图放在U盘根目录下的QQD文件夹下", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "请将图放在U盘根目录下的QQD文件夹下！" + filePath, Toast.LENGTH_SHORT).show();
        }
    }

    private String getExternalStorageDirectories() {
        List<String> mountedSDCardPaths = SDCardUtils.getMountedSDCardPath();
        for (int i = 0; i < mountedSDCardPaths.size(); i++) {
            if (mountedSDCardPaths.get(i).contains("mnt")) {
                return mountedSDCardPaths.get(i);
            }
        }
        return null;
    }


    private boolean isImageFile(String path) {
        String[] imageExtensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp"};
        for (String extension : imageExtensions) {
            if (path.toLowerCase().endsWith(extension)) {
                return true;
            }
        }
        return false;
    }


    private void setupViewPager() {
        viewPager = findViewById(R.id.viewPager);
        InfiniteImagePagerAdapter adapter = new InfiniteImagePagerAdapter(this, imagePaths);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(adapter.getInitialPosition());

        runnable = new Runnable() {
            @Override
            public void run() {
                int currentItem = viewPager.getCurrentItem();
                int nextItem = currentItem + 1;
                viewPager.setCurrentItem(nextItem, true);
                handler.postDelayed(this, 60000); // 3秒切换一次
            }
        };
    }

    @Override
    protected void onResume() {
        super.onResume();
        handler.postDelayed(runnable, 60000); // 开始轮播
    }

    @Override
    protected void onPause() {
        super.onPause();
        handler.removeCallbacks(runnable); // 停止轮播
    }

}